angular.module('PackingStorage')

.controller('PackingStorage.HomeCtrl', ['$scope', '$state', '$timeout', 'User', 'Device', 'imanDialog', 'PackingStorageHomeService', 'isSanner', '$ionicModal',
    function($scope, $state, $timeout, User, Device, imanDialog, PackingStorageHomeService, isSanner, $ionicModal) {
        $scope.data = {};
        $scope.homeData = {
            houses: [],
            selectHouse: ''
        };
        var wareHouseId = '';
        $scope.packCode = ""; //包装

        $ionicModal.fromTemplateUrl(u9ImPDA.getFullPath('tpls/packingStorage.setting.html', 'PackingStorage'), {
            scope: $scope,
            animation: 'slide-in-right'
        }).then(function(modal) {
            $scope.modal = modal;
        });

        function init() {
            var wareHouse = angular.fromJson(window.localStorage.getItem("PackingStorageWareHouse"));
            if (wareHouse) {
                initData(wareHouse);
            }
        }

        init();

        $scope.startScan = function() {
            $state.go('PackingStorage-bats', {
                packData: $scope.packCode + "&" + wareHouseId
            });
        };

        $scope.gethouses = function() {
            imanDialog.showLoading();
            PackingStorageHomeService.getAllWareHouse().then(function(data) {
                imanDialog.hideLoading();
                if (data) {
                    $scope.homeData.houses = data;
                    $scope.modal.show().then(function() {

                    });
                }
            }, function(error) {
                imanDialog.toastBottom(error);
                imanDialog.hideLoading();
            });
        };

        function initData(wareHouse) {
            $scope.homeData.selectHouse = wareHouse.Name;
            wareHouseId = wareHouse._id;
            window.localStorage.setItem("PackingStorageWareHouse", angular.toJson(wareHouse));
            if ($scope.modal) {
                $scope.modal.hide();
            }
        }
        $scope.initData = function(wareHouse) {
            initData(wareHouse);
        };

        $scope.$on('$ionicView.afterEnter', function() {
            isSanner.open();
        });
        $scope.$on('$ionicView.beforeLeave', function() {
            isSanner.close();
        });

        $scope.$on('iScanner.DataReceived', function(e, data) {
            var barcode = data;
            $scope.packCode = barcode; //包装
            $scope.$apply();
        });
    }
]);
